package com.su.kddq.productor;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * MQ 生产
 * @author sx
 */
@Component
public class OrderProductor implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        //必须为true,否则无法触发returnedMessage回调，消息丢失
        rabbitTemplate.setMandatory(true);
        //指定 ReturnCallback
        rabbitTemplate.setReturnCallback(this);
        //指定 ConfirmCallback
        rabbitTemplate.setConfirmCallback(this);
    }


    /**
     * 消息确认入机回调
     * @param correlationData
     * @param b
     * @param s
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if (b) {
            System.out.println("ack");
        } else {
            System.out.println("nack");
        }
    }

    /**
     * 发送消息
     * @param map
     * @param exchange
     * @param routingKey
     */
    public void SendOrderMes(Map map, String exchange, String routingKey) {
        String body = JSON.toJSONString(map);
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setDeliveryTag(RandomUtils.nextLong());
        Message message = new Message(body.getBytes(), messageProperties);
        rabbitTemplate.convertAndSend(exchange, routingKey, message);
    }

    /**
     * 消息确认入队回调
     * @param message
     * @param i
     * @param s
     * @param s1
     * @param s2
     */
    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {

    }
}
